import React, { useState, useEffect } from 'react';
import {
  Input,
  Form,
  Upload,
  Button,
  message,
  Progress,
  Modal,
  List,
  Space,
  Card,
  Typography
} from 'antd';
import {
  InboxOutlined,
  DownloadOutlined,
  DeleteOutlined,
  UploadOutlined
} from '@ant-design/icons';
import axios from 'axios';

const { TextArea } = Input;
const { Dragger } = Upload;
const { Text } = Typography;

const CompZpRename = () => {
  // 状态管理
  const [schoolName, setSchoolName] = useState('');
  const [fileList, setFileList] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [uploadPercent, setUploadPercent] = useState(0);
  const [downloadModal, setDownloadModal] = useState({ visible: false, id: null });
  const [deleteModal, setDeleteModal] = useState({ visible: false, id: null });
  const [downloadCode, setDownloadCode] = useState('');
  const [deleteCode, setDeleteCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [studentInfo, setStudentInfo] = useState('');

  // 获取已转换文件列表
  const fetchFileList = async () => {
    try {
      const response = await axios.get('/api/pdfRename/haveTranslatedList');
      console.log(response.data);
      setFileList(response.data);
      console.log(fileList);
    } catch (error) {
      message.error('获取文件列表失败');
    }
  };

  useEffect(() => {
    fetchFileList();
  }, []);

  // 自定义上传函数
  const customUpload = async (options) => {
    const { file, onProgress, onSuccess, onError } = options;

    if (!schoolName.trim() || !studentInfo.trim()) {
      message.error('请先输入学校名称');
      onError(new Error('请完整填写学校名称和学生信息'));
      return;
    }

    const formData = new FormData();
    formData.append('file', file);
    formData.append('schoolName', schoolName);
    formData.append('studentInfo', studentInfo);

    setUploading(true);
    setUploadPercent(0);

    try {
      const response = await axios.post('/api/pdfRename/pdfRenameUpload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          setUploadPercent(percentCompleted);
          onProgress({ percent: percentCompleted });
        },
      });

      const { code } = response.data;
      message.success(`上传成功！下载码：${code}`);
      onSuccess(response.data);
      fetchFileList(); // 刷新列表
    } catch (error) {
      message.error('上传失败');
      onError(error);
    } finally {
      setUploading(false);
      setUploadPercent(0);
    }
  };

  // 下载文件
  const handleDownload = async () => {
    if (!downloadCode.trim()) {
      message.error('请输入下载码');
      return;
    }

    setLoading(true);
    try {
      const response = await axios.get(`/api/haveTranslated/${downloadModal.id}`, {
        params: { code: downloadCode },
        responseType: 'blob',
      });

      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `file_${downloadModal.id}.pdf`);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);

      message.success('下载成功');
      setDownloadModal({ visible: false, id: null });
      setDownloadCode('');
    } catch (error) {
      message.error('下载码错误或下载失败');
    } finally {
      setLoading(false);
    }
  };

  // 删除文件
  const handleDelete = async () => {
    if (!deleteCode.trim()) {
      message.error('请输入删除码');
      return;
    }

    setLoading(true);
    try {
      await axios.delete(`/api/delTranslated/${deleteModal.id}`, {
        params: { code: deleteCode },
      });

      message.success('删除成功');
      setFileList(fileList.filter(item => item.id !== deleteModal.id));
      setDeleteModal({ visible: false, id: null });
      setDeleteCode('');
    } catch (error) {
      message.error('删除码错误或删除失败');
    } finally {
      setLoading(false);
    }
  };

  // 上传组件配置
  const uploadProps = {
    name: 'file',
    multiple: false,
    customRequest: customUpload,
    showUploadList: false,
    accept: '.zip',
    beforeUpload: (file) => {
      const isZip = file.type === 'application/zip' ||
        file.name.endsWith('.zip');
      if (!isZip) {
        message.error('只能上传 zip 压缩包！');
        return Upload.LIST_IGNORE;   // 直接拦截
      }
      return true;
    },
  };

  return (
    <div style={{ padding: '24px', maxWidth: '800px', margin: '0 auto' }}>
      <Card title="综评重命名" style={{ marginBottom: 24 }}>
        {/* 学校名称输入框 */}
        <div style={{ marginBottom: 24 }}>
          <Text strong>学校名称：</Text>
          <Input
            placeholder="请输入学校名称"
            value={schoolName}
            onChange={(e) => setSchoolName(e.target.value)}
            style={{ width: 300, marginLeft: 8 }}
          />
        </div>
        {/* 学生信息输入框 */}
        <div style={{ marginBottom: 24 }}>
          <Text strong>学生信息：</Text>
          <div style={{ marginBottom: 24 }}>
            <Text strong>学生信息：</Text>
            <TextArea
              placeholder="320621202001010202张三"
              value={studentInfo}
              onChange={(e) => setStudentInfo(e.target.value)}
              style={{ width: 300, marginLeft: 8, minHeight: 60 }}
              autoSize={{ minRows: 2, maxRows: 4 }}
            />
          </div>
        </div>
        {/* 文件上传区域 */}
        <div style={{ marginBottom: 32 }}>
          <Dragger {...uploadProps} disabled={uploading}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">点击或拖拽zip文件到此处上传</p>
            <p className="ant-upload-hint">
              只支持单个zip文件上传，传输其他格式文件会解析错误，上传前请确保已输入学校名称
            </p>
          </Dragger>

          {/* 上传进度条 */}
          {uploading && (
            <div style={{ marginTop: 16 }}>
              <Progress
                percent={uploadPercent}
                status="active"
                strokeColor={{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }}
              />
            </div>
          )}
        </div>

        {/* 已转换文件列表 */}
        <div>
          <Text strong style={{ fontSize: 16 }}>已转换文件列表：</Text>
          <List
            style={{ marginTop: 16 }}
            bordered
            dataSource={fileList}
            renderItem={(item) => (
              <List.Item
                actions={[
                  <Button
                    type="primary"
                    icon={<DownloadOutlined />}
                    size="small"
                    onClick={() => setDownloadModal({ visible: true, id: item.id })}
                  >
                    下载
                  </Button>,
                  <Button
                    danger
                    icon={<DeleteOutlined />}
                    size="small"
                    onClick={() => setDeleteModal({ visible: true, id: item.id })}
                  >
                    删除
                  </Button>,
                ]}
              >
                <List.Item.Meta
                  title={item}
                />
              </List.Item>
            )}
            locale={{ emptyText: '暂无已转换文件' }}
          />
        </div>
      </Card>

      {/* 下载确认弹窗 */}
      <Modal
        title="输入下载码"
        open={downloadModal.visible}
        onOk={handleDownload}
        onCancel={() => {
          setDownloadModal({ visible: false, id: null });
          setDownloadCode('');
        }}
        confirmLoading={loading}
      >
        <Input
          placeholder="请输入下载码"
          value={downloadCode}
          onChange={(e) => setDownloadCode(e.target.value)}
          onPressEnter={handleDownload}
        />
      </Modal>

      {/* 删除确认弹窗 */}
      <Modal
        title="输入删除码"
        open={deleteModal.visible}
        onOk={handleDelete}
        onCancel={() => {
          setDeleteModal({ visible: false, id: null });
          setDeleteCode('');
        }}
        confirmLoading={loading}
        okButtonProps={{ danger: true }}
      >
        <Input
          placeholder="请输入删除码"
          value={deleteCode}
          onChange={(e) => setDeleteCode(e.target.value)}
          onPressEnter={handleDelete}
        />
      </Modal>
    </div>
  );
};

export default CompZpRename;
